package com.power.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.power.contant.ManagerConstants;
import com.power.domain.SysMenu;
import com.power.mapper.SysMenuMapper;
import com.power.service.SysMenuService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {


    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Set<SysMenu> selectSysMenuListByUserId(Long userId) {
        //从redis中获取权限的集合
        String jsonStr = stringRedisTemplate.opsForValue().get(ManagerConstants.LOGIN_SYS_MENU_PREFIX + userId);
        Set<SysMenu> menuSet = null;
        if (StringUtils.hasText(jsonStr)) {
            //将JSON格式的字符串的集合数据转为set集合
            List<SysMenu> sysMenus = JSONObject.parseArray(jsonStr, SysMenu.class);
            menuSet = sysMenus.stream().collect(Collectors.toSet());
        } else {//从数据中获取
            menuSet = sysMenuMapper.selectSysMenuListByUserId(userId);
            //将菜单集合转换为JSON格式的字符串
            stringRedisTemplate.opsForValue().set(ManagerConstants.LOGIN_SYS_MENU_PREFIX + userId, JSON.toJSONString(menuSet), Duration.ofHours(18));
        }
        //将集合转换为树结构
        return TransformTree(menuSet, 0L);
    }

    private Set<SysMenu> TransformTree(Set<SysMenu> menus, long pId) {
        //已知菜单深度<=2
        //先获取根节点
        /*Set<SysMenu> roots = menus.stream()
                .filter(m -> m.getParentId().equals(pId))
                .collect(Collectors.toSet());
        //孩子结点
        roots.forEach(r -> {
            Set<SysMenu> child = menus.stream().filter(m -> m.getParentId().equals(r.getMenuId())).collect(Collectors.toSet());
            r.setList(child);
        });*/


        //未知菜单深度
        //获取根节点
        Set<SysMenu> roots = menus.stream()
                .filter(m -> m.getParentId().equals(pId))
                .collect(Collectors.toSet());
        roots.forEach(r ->r.setList(TransformTree(menus,r.getMenuId()))); // 递归找
        return roots;
    }
}
